# encoding:utf8
import sys
sys.path.append(".")

import web
import datetime
import json
import subprocess  

urls = (
    "/cmd/(.+)", "Cmd",
    '/', 'Index',
)

CMDS = {}

def loadCMDs():
    fp = open('cmds.json', 'r')
    data = json.load(fp)
    fp.close()

    for cmd in data:
        CMDS[cmd['name']] = cmd

loadCMDs()

def success(data = None):
    result = {'error':{}, 'result':data}
    web.header('Content-Type', 'application/json')
    return json.dumps(result)

def fail(code = -1, msg = 'request error.', data = None):
    result = {'error':{'code': code, 'msg':msg}, 'result':data}
    web.header('Content-Type', 'application/json')
    return json.dumps(result)

def Run(cmd, param):
    cmdFile = CMDS[cmd]['cmd']
    args = ['python', 'cmds/%s' % cmdFile]
    print args
    if not param is None:
        args = args + param
    p = subprocess.Popen(args,stdout=subprocess.PIPE)  
    return p.stdout.read()

class Cmd:
    def GET(self, param='default'):
        global CMDS
        if param == 'default':
            return fail(code=-1, msg='No cmd name.')
        components = param.split('/')
        cmd = components[0]
        if not CMDS.has_key(cmd):
            return fail(code=-1, msg='Cmd %s is not registed.' % cmd)
        cmdParam = None
        if len(components) > 1:
            cmdParam = components[1:]

        web.header('Content-Type', 'application/json')
        return Run(cmd, cmdParam)

class Index:
    def GET(self):
        today = datetime.datetime.today()
        day = today.strftime("%y%m%d")
        return day


if __name__ == "__main__":
    app = web.application(urls, globals())
    app.run()